import asyncio

import aioredis
import pymongo
import time
import redis
from cmcc_10086 import gen_nonce_str
from cmcc_10086 import reg, login
import os

conn = redis.Redis()
client = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db = client.cs_recharge
coll = db.cmcc_username
loop = asyncio.get_event_loop()
asy_redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
while True:
    res = coll.find({"is_reg": "0"})
    for obj in res:
        try:
            username = obj['username']
            if os.path.isfile('/app/log/cmcc_username/' + username):
                # conn.lrem('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
                # conn.rpush('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
                continue
            task = asyncio.ensure_future(login(obj['username'], obj['passwd'], asy_redis))
            res = loop.run_until_complete(task)
            print(obj)
            print(res)
            if '账户名与密码不匹配' in res['message']:
                print(obj)
                conn.lrem('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
                coll.update_one({"username": obj["username"]}, {"$set": {"is_reg": '2'}})
            elif res['code'] == 0:
                conn.lrem('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
                conn.rpush('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
            # else:
            #     conn.lrem('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
            #     conn.rpush('cmcc_user', '%s|%s|0' % (obj['username'], obj['passwd']))
        except Exception as e:
            print(e)
    print("===================")
    time.sleep(30*60)
